/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DepInsertPanel.java
 *
 * Created on 28/11/2011, 16:50:25
 */

package proj5labbd.graphics.dependente;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.MainFrame;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Painel destinado à inserção de dependentes na base de dados
 */
public class DepInsertPanel extends OperationPanel {

    /** Creates new form DepInsertPanel */
    public DepInsertPanel(DepFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbInsert.addActionListener(new DepAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnParam = new javax.swing.JPanel();
        jlbNome = new javax.swing.JLabel();
        jtxtNome = new javax.swing.JTextField();
        jlbDataNasc = new javax.swing.JLabel();
        jlbSexo = new javax.swing.JLabel();
        jcbSexo = new javax.swing.JComboBox();
        jlbFuncionario = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtFuncionario = new javax.swing.JTable();
        jftxtDate = new javax.swing.JFormattedTextField();
        jbInsert = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Inserção"));
        setPreferredSize(new java.awt.Dimension(614, 469));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnParam.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de inserção"));

        jlbNome.setText("Nome Completo");

        jlbDataNasc.setText("Data de Nascimento");

        jlbSexo.setText("Sexo");

        jcbSexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "F", "M" }));

        jlbFuncionario.setText("Funcionário");

        jtFuncionario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtFuncionario);

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        javax.swing.GroupLayout jpnParamLayout = new javax.swing.GroupLayout(jpnParam);
        jpnParam.setLayout(jpnParamLayout);
        jpnParamLayout.setHorizontalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE)
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbFuncionario)
                        .addContainerGap(466, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnParamLayout.createSequentialGroup()
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlbNome, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(25, 25, 25)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbDataNasc, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)
                            .addComponent(jftxtDate, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbSexo)
                            .addComponent(jcbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
        );
        jpnParamLayout.setVerticalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbSexo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jcbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jlbNome)
                            .addComponent(jlbDataNasc))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbFuncionario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbInsert.setText("Inserir");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(512, Short.MAX_VALUE)
                .addComponent(jbInsert, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jpnParam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jpnParam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 100, Short.MAX_VALUE)
                .addComponent(jbInsert))
        );
    }// </editor-fold>//GEN-END:initComponents

    //atua a partir da apresentação do painel ao usuário
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            frame.printException(ex);
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações da tabela");
        }
    }//GEN-LAST:event_formComponentShown

    //atua a partir do click do mouse no painel
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtFuncionario.clearSelection();
    }//GEN-LAST:event_formMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbInsert;
    private javax.swing.JComboBox jcbSexo;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JLabel jlbDataNasc;
    private javax.swing.JLabel jlbFuncionario;
    private javax.swing.JLabel jlbNome;
    private javax.swing.JLabel jlbSexo;
    private javax.swing.JPanel jpnParam;
    private javax.swing.JTable jtFuncionario;
    private javax.swing.JTextField jtxtNome;
    // End of variables declaration//GEN-END:variables

    //configura a(s) tabela(s) a partir de dados resgatados da base de dados
    public void setupTable() throws SQLException {
        String [] titles = {"ID","Funcionário"};
        String [] fields = {"idFu","nomeCompletoFu"};
        String[][] result = dbInterface.view(fields, null, new String[]{"funcionario"});
        DefaultTableModel model = new DefaultTableModel(result,titles);
        jtFuncionario.setModel(model);
    }

    //ouvite do btão de insert
    class DepAction implements ActionListener {

        //ação do botão de insert
        public void actionPerformed(ActionEvent e) {
        if ( jtFuncionario.getSelectedRowCount() == 1 && jtxtNome.getText().trim() != "") {
                    ArrayList<String> params = new ArrayList<String>();
                    ArrayList<String> fields = new ArrayList<String>();

                    params.add("'"+jtxtNome.getText()+"'");
                    fields.add("nomeCompletoDe");
                    

                    if (jftxtDate.getText() != "  -  -    ") {
                        params.add("TO_DATE('"+jftxtDate.getText()+"','DD-MM-YYYY')");
                        fields.add("dataNascimentoDe");
                    }
                    params.add("'"+(String)jcbSexo.getSelectedItem()+"'");
                    fields.add("sexoDe");

                    params.add((String)jtFuncionario.getValueAt(jtFuncionario.getSelectedRow(), 0));
                    fields.add("idFu");

                    String [] paramArray = new String[params.size()];
                    String [] fieldArray = new String[fields.size()];

                    params.toArray(paramArray);
                    fields.toArray(fieldArray);
                    try {
                        dbInterface.insert(fieldArray, paramArray, new String[]{"dependente"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao tentar inserir a tupla.");
                    }

                }
                else if (jtFuncionario.getSelectedRowCount() != 1) {
                    JOptionPane.showMessageDialog(null, "Você deve escolher um tipo de funcionário.");
                }
                else if (jtxtNome.getText().trim() == "") {
                    JOptionPane.showMessageDialog(null, "Você deve inserir o nome do dependente.");
                }



        }

            }
   


}
